package com.bj58.ecdata.mailreport.threads;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import com.bj58.ecdata.mailreport.cache.ServiceBeanFactory;
import com.bj58.ecdata.mailreport.db.CommonDao;
import com.bj58.ecdata.mailreport.db.DBConfig;
import com.bj58.ecdata.mailreport.model.IESend;
import com.bj58.ecdata.mailreport.service.impl.IESendService;
import com.bj58.ecdata.mailreport.util.DateUtil;
import com.bj58.ecdata.mailreport.util.MailUtil;
import com.bj58.ecdata.mailreport.util.SubmitSms;

public class IESendThread  extends Thread{
	private IESendService IESendService = (IESendService) ServiceBeanFactory.get(IESend.class,IESendService.class);
	
	
	@SuppressWarnings("static-access")
	public void run(){
		try {
			CommonDao comDao = new CommonDao();
			String resetSQL= "update ie_send set sendState=0 where sendState=2;";
			comDao.executeUpdate(resetSQL, DBConfig.db_manage.getIntType());
			while(true){
				/**  step 1: 取出 state = 1
				 *    step 2: 校验发送时间 是否在未来4分钟内　校验发送频率　判断是否应该发送    
				 *    step 3: 设置TimerTask发送邮件  并将发送状态改为2 （发送中）　
				 */
				IESendTimerTask.getLogger().info("The thread is running~"+DateUtil.getStringDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
				List<IESend> tempSendList = IESendService.getListByCon(" state = 1 and sendState !=2 ");
				if(null != tempSendList && !tempSendList.isEmpty()){
					List<IESend> sendList = new ArrayList<IESend>(); //筛选后的发送队列
					String today=DateUtil.getStringDate(new Date(), "yyyy-MM-dd");
					String nowTime = DateUtil.getStringDate(new Date(), "HH:mm:ss");
					for (IESend vo : tempSendList) {
						String updateTime=vo.getUpdateTime();
						String updateDay="";
						if(updateTime !=null && !"".equals(updateTime.trim())){
							updateDay= updateTime.substring(0, updateTime.indexOf(" "));
						}

						if(shouleSend(vo,nowTime,today,updateDay)){
							sendList.add(vo);
						}
					}
					
					if(null != sendList && !sendList.isEmpty()){
						IESendTimerTask.getLogger().info("Have " + sendList.size() +"  record   to send~");
						//检测此时状态为“发送中”的邮件数量，若大于一定数量，则先不对要进行定时
						for (IESend ieSend : sendList) {
							
//							int countSend=0;
//							for (IESend s : sendList) {
//								if(s.getSendState()==2)
//									countSend++;									
//							}
//							if(countSend>10)
//								break;
						
							Timer timer = new Timer();
							String sendTime = DateUtil.getStringDate(new Date(), "yyyy-MM-dd");
							sendTime = sendTime + " " + ieSend.getSendTime().trim();
							IESendTimerTask.getLogger().info(sendTime);
							timer.schedule(new IESendTimerTask(ieSend,null,false,null), DateUtil.strToDate(sendTime, "yyyy-MM-dd HH:mm:ss"));
							ieSend.setSendState(6); //更新状态:等待
							ieSend.setUpdateTime(DateUtil.getStringDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
							IESendService.updateVo(ieSend);
						}
					}
				}
				IESendTimerTask.getLogger().info("sleeping for 5 minutes...");
				this.sleep(5*60*1000);
			}
		} catch (Exception e) {
			IESendTimerTask.getLogger().error("fatal error occurs:"+DateUtil.getStringDate(new Date(), "yyyy-MM-dd HH:mm:ss"),e);
			//短信报警
			Map<String,String> sendMap = new HashMap<String, String>();
        	sendMap.put("13811583416","自定义邮件系统报错，请及时查看重启!");
        	sendMap.put("15726690526","自定义邮件系统报错，请及时查看重启!");
        	SubmitSms.submitMsg(sendMap);
        	MailUtil.javaMailSend("[重要]自定义邮件系统报错", "自定义邮件系统报错，请及时查看重启!","huangliang@58.com;guoxue@58.com", null);
		}
	}
	
	public static boolean shouleSend(IESend vo,String nowTime, String today, String updateDay) {
		//更新时间为今日，且已发送状态为1:成功，4:预警， 5:待人工处理(如550邮箱失效) , 这些情况不需要再次发送了
		if(today.equals(updateDay) && (vo.getSendState()==1 || vo.getSendState()==4 ||  vo.getSendState()==5))
			return false;
		
		//校验发送时间
		String sendTime = vo.getSendTime();
		double sec  =(double) (DateUtil.strToDate(nowTime, "HH:mm:ss").getTime() + 6*60*1000 - DateUtil.strToDate(sendTime, "HH:mm:ss").getTime()) / 1000 ;

		//未来6分钟要发送，之前已经将其加入等待状态，再加就重复了
		if(today.equals(updateDay) && vo.getSendState()==6 && sec >= 0 && sec <= 6 * 60){
			return false;
		}
		//未来5分钟且未发送的加入,之前5分钟失败的重新执行 //today.equals(updateDay)
		if((sec >= 0 && sec <= 6 * 60) || (sec >= 11 * 60 && sec < 11*60*60)){ 
			//校验发送频率
			String sendFre = vo.getSendFre();
			int numOfWeek = DateUtil.getWeekOfDate(new Date());
			if("day".equals(sendFre)){ //每日发送
				return true;
			}else if("week".equals(sendFre) && numOfWeek == 1){ //每周1
				return true;
			}else{ //自定义
				if(sendFre.contains(String.valueOf(numOfWeek))){
					return true;
				}
			}
		}
		return false;
	}
	
	public static void main(String[] args) {
		try {
			MailUtil.initSCF();//SCF初始化 扫包
			IESendThread  thread = new IESendThread();
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
	
}
